from django.http import HttpResponse, JsonResponse
from django.views import View
from django_redis import get_redis_connection

from libs.yuntongxun.sms import CCP


# Create your views here.

class ImageCodeView(View):
    def get(self, request, uuid):
        # 生成图片验证码
        from libs.captcha.captcha import captcha
        text, image = captcha.generate_captcha()
        # 保存图片验证码
        redis_conn = get_redis_connection('code')
        redis_conn.setex(uuid, 100, text)
        # 返回图片验证码
        return HttpResponse(image, content_type='image/jpeg')

class SmsCodeView(View):
    def get(self, request, mobile):
        # 接收参数
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 校验参数
        if not all([image_code, uuid]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        # 获取redis中的图片验证码
        redis_conn = get_redis_connection('code')
        redis_image_code = redis_conn.get(uuid)
        if redis_image_code is None:
            return JsonResponse({'code': 400, 'errmsg': '图片验证码已过期'})
        if redis_image_code.decode().lower() != image_code.lower():
            return JsonResponse({'code': 400, 'errmsg': '图片验证码错误'})
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag is not None:
            return JsonResponse({'code': 429, 'errmsg': '发送短信过于频繁'})

        # 生成短信验证码
        from random import randint
        sms_code = '%04d' % randint(0, 9999)

        #redis管道技术 优化性能
        pipeline = redis_conn.pipeline()
        pipeline.setex(mobile, 300, sms_code)
        # 添加一个标记，表示此手机号已发送过短信验证码
        pipeline.setex('send_flag_%s'%mobile, 60, 1)
        # 执行管道
        pipeline.execute()

        # 发送短信验证码
        CCP().send_template_sms(mobile, [sms_code, 5], 1)
        return JsonResponse({'code': 0, 'errmsg': '发送短信成功'})